package com.baseweb.webadmin.controller.web;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.ExampleType;
import com.baseweb.webadmin.core.constants.UserType;
import com.baseweb.webadmin.core.model.bvo.ByUserExampleBvo;
import com.baseweb.webadmin.core.model.bvo.ByUserRecommendBvo;
import com.baseweb.webadmin.core.model.bvo.UserInfoBvo;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.*;
import com.baseweb.webadmin.service.UserService;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zx on 2017/7/29.
 */
@Controller
@RequestMapping("/htmlWeb/")
public class ExampleManageController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(HtmlTrolleyController.class);

    @Autowired
    private UserService userService;

    /**
     * 分页查询作品
     * @param request
     * @param requestPage
     * @param exampleBvo
     * @param flag
     * @return
     */
    @RequestMapping("getExamplePageList")
    @ResponseBody
    public ResultPage<ByUserExampleBvo> getExamplePageList(HttpServletRequest request, RequestPage requestPage, ByUserExampleBvo exampleBvo,
                                                           @RequestParam(value = "flag",required = false)String flag,
                                                           @RequestParam(value = "viewFlag",required = false)String viewFlag){
        Object temp = request.getSession().getAttribute("login_id");
        Integer userId = temp == null ? 0 : Integer.valueOf(temp.toString());
        exampleBvo = exampleBvo == null ? new ByUserExampleBvo() : exampleBvo;
        UserInfoBvo userInfoBvo = exampleBvo.getUserInfoBvo() == null ? new UserInfoBvo() : exampleBvo.getUserInfoBvo();
        if(userInfoBvo.getId() == null && userId > 0){
            userInfoBvo.setId(userId);
        }
        if(StringUtil.isNotBlank(viewFlag)){
            userInfoBvo.setId(null);
        }
        if("admin".equals(flag)){//我的作品查询所有案例
            userInfoBvo.setId(null);
            String userType = String.valueOf(request.getSession().getAttribute("login_type"));
            if(!(UserType.SUPER_ADMIN.getCode() + "").equals(userType)){
                List<ByOpenCity> byOpenCityList = userService.findAllAreaByUserId(userId);
                String area = "";
                int i = 0;
                for(ByOpenCity city : byOpenCityList){
                    if(i == 0){
                        area += "'" + city.getArea() + "'";
                    }else{
                        area += ",'" + city.getArea() + "'";
                    }
                    i++;
                }
                userInfoBvo.setArea(area);
            }
        }
        exampleBvo.setUserInfoBvo(userInfoBvo);
        List<ByUserExampleBvo> list = userService.selectExampleBvoListByPage(exampleBvo,requestPage);
        if(StringUtil.isNotBlank(viewFlag) && list.size() > 0){
            ByUserExampleBvo caseVo = list.get(0);
            caseVo.setViewCount(caseVo.getViewCount() == null ? 1 : caseVo.getViewCount() + 1);
            caseVo.setUserId(caseVo.getUserInfoBvo().getId());
            userService.insertExample(caseVo);
        }
        return new ResultPage<>(requestPage.getTotal(),requestPage.getPageSize(),requestPage.getCurPage(),list);
    }

    /**
     * 设置作品状态
     * @param id
     * @param status
     * @return
     */
    @RequestMapping(value = "/updateExampleView")
    @ResponseBody
    public String passExampleView(@RequestParam(value = "id",required = true) Integer id,
                                  @RequestParam(value = "status",defaultValue = "1") Integer status) {

        if (id != null && id > 0){
            ByUserExample byUserExample = userService.findExample(id);
            if(status != null)
                byUserExample.setStatus(status);

            userService.insertExample(byUserExample);
        }

        return "success";
    }

    /**
     * 添加案例/视频
     * @param request
     * @param id
     * @param file
     * @param name
     * @param descn
     * @param status
     * @param example_type
     * @param case_time
     * @param case_hotel
     * @param case_comment
     * @param caseType
     * @param caseEnvironment
     * @param case_detail
     * @return
     */
    @RequestMapping(value = "/submitExample")
    @ResponseBody
    public String submitInvite(HttpServletRequest request,@RequestParam(value = "id",required = false) Integer id,
                               @RequestParam(value = "file",required = false) MultipartFile file,
                               @RequestParam(value = "name",required = false) String name,
                               @RequestParam(value = "descn",required = false) String descn,
                               @RequestParam(value = "status",defaultValue = "0") Integer status,
                               @RequestParam(value = "example_type",required = false) Integer example_type,
                               @RequestParam(value = "case_time",required = false) String case_time,
                               @RequestParam(value = "case_hotel",required = false) String case_hotel,
                               @RequestParam(value = "case_comment",required = false) String case_comment,
                               @RequestParam(value = "caseType",required = false) String caseType,
                               @RequestParam(value = "caseEnvironment",required = false) String caseEnvironment,
                               @RequestParam(value = "case_detail",required = false) String case_detail) {
        try{
            Object temp = request.getSession().getAttribute("login_id");
            Integer userId = temp == null ? 0 : Integer.valueOf(temp.toString());
            ByUserExample byUserExample = null;
            if (id != null && id > 0){
                byUserExample = userService.findExample(id);
            }else{
                byUserExample = new ByUserExample();
            }

            byUserExample.setUserId(userId);
            byUserExample.setName(name);
            byUserExample.setDescn(descn);
            byUserExample.setStatus(status);
            byUserExample.setExampleType(example_type);
//            byUserExample.setStatus(BaseState.DELETE.getCode());
            byUserExample.setCreateTime(new DateTime());
            byUserExample.setUpdateTime(new DateTime());

            if (example_type.intValue() == ExampleType.CASE.getCode()){
                byUserExample.setCaseTime(case_time);
                byUserExample.setCaseHotel(case_hotel);
                byUserExample.setCaseComment(case_comment);
                byUserExample.setCaseDetail(case_detail);
                byUserExample.setCaseType(caseType);
                byUserExample.setCaseEnvironment(caseEnvironment);
            }

            if (file != null && file.getSize() > 0){
                if(file.getSize()>10000000)
                {
                    throw new Exception("上传失败：文件大小不能超过10M");
                }

                String fileName = file.getOriginalFilename();
                int  indexdot =  fileName.lastIndexOf(".");
                String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+fileName.substring(indexdot);

//                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
                UploadUtil.uploadData(file.getBytes(), img_url);
                byUserExample.setImgUrl(img_url);
            }

            userService.insertExample(byUserExample);

        }catch (Exception ex){
            ex.printStackTrace();
        }

        return "success";
    }

    /**
     * 分页查询作品列表下的图片
     * @param request
     * @param requestPage
     * @param example_id
     * @return
     */
    @RequestMapping(value = "/getMyExampleDetailList")
    @ResponseBody
    public ResultPage<ByUserExampleDetail> getExampleDetailList(HttpServletRequest request, RequestPage requestPage,
                                     @RequestParam(value = "example_id", required = false) Integer example_id) {

        Object temp = request.getSession().getAttribute("login_id");
        Integer userId = temp == null ? null : Integer.valueOf(temp.toString());
        List<ByUserExampleDetail> list = userService.selectExampleDetailListByPage(null, example_id, null, requestPage.getStart(), requestPage.getPageSize());
        int total = userService.selectExampleDetailListCount(userId,example_id,null);
        return new ResultPage<>(total,requestPage.getPageSize(),requestPage.getCurPage(),list);
    }

    /**
     * 添加作品列表下的图片
     * @param request
     * @param id
     * @param example_id
     * @param file
     * @param name
     * @param status
     * @return
     */
    @RequestMapping(value = "/submitExampleDetail")
    @ResponseBody
    public Map<String, Object> submitExampleDetail(HttpServletRequest request, @RequestParam(value = "id",required = false) Integer id,
                                                   @RequestParam(value = "example_id",required = false) Integer example_id,
                                                   @RequestParam(value = "file",required = false) MultipartFile file,
                                                   @RequestParam(value = "name",required = false) String name,
                                                   @RequestParam(value = "status",defaultValue = "1") Integer status) {
        try{
            ByUserExampleDetail byUserExampleDetail = null;
            if (id != null && id > 0){
                byUserExampleDetail = userService.findExampleDetail(id);
            }else{
                byUserExampleDetail = new ByUserExampleDetail();
            }

            Object temp = request.getSession().getAttribute("login_id");
            Integer userId = temp == null ? 0 : Integer.valueOf(temp.toString());
            byUserExampleDetail.setUserId(userId);
            byUserExampleDetail.setName(name);
            byUserExampleDetail.setExampleId(example_id);
            byUserExampleDetail.setStatus(status);
            byUserExampleDetail.setCreateTime(new DateTime());
            byUserExampleDetail.setUpdateTime(new DateTime());

            if (file != null && file.getSize() > 0){
                if(file.getSize()>10000000)
                {
                    throw new Exception("上传失败：文件大小不能超过10M");
                }

                String fileName = file.getOriginalFilename();
                int  indexdot =  fileName.lastIndexOf(".");
                String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+fileName.substring(indexdot);

//                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
                UploadUtil.uploadData(file.getBytes(), img_url);
                byUserExampleDetail.setImgUrl(img_url);
            }
            userService.insertExampleDetail(byUserExampleDetail);

        }catch (Exception ex){
            ex.printStackTrace();
            return fail("");
        }
        return success("");
    }

    /**
     * 获取作品列表下的图片详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/getExampleDetail")
    @ResponseBody
    public ByUserExampleDetail getExampleDetail(@RequestParam(value = "id",required = false) Integer id){
        return userService.findExampleDetail(id);
    }

    /**
     * 删除作品列表下的图片
     * @param id
     * @param example_id
     * @return
     */
    @RequestMapping(value = "/deleteExampleDetail")
    @ResponseBody
    public Map<String, Object> deleteExampleDetail(@RequestParam(value = "id",required = true) Integer id,
                                      @RequestParam(value = "example_id",required = false) Integer example_id) {
        try{
            if (id != null && id > 0){
                userService.deleteExampleDetail(id);
            }else{
                return fail("");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return fail("");
        }

        return success("");
    }

    /**
     * 推荐分页查询
     * @param request
     * @param requestPage
     * @param example_id
     * @return
     */
    @RequestMapping(value = "/getRecommendUserList")
    @ResponseBody
    public ResultPage<ByUserRecommendBvo> getRecommendUserList(HttpServletRequest request, RequestPage requestPage,
                                     @RequestParam(value = "example_id", required = false) Integer example_id) {

        Object temp = request.getSession().getAttribute("login_id");
        Integer userId = temp == null ? null : Integer.valueOf(temp.toString());
        List<ByUserRecommendBvo> list = userService.selectByUserRecommendBvoListByPage(null,null,example_id,requestPage);

        return new ResultPage<>(requestPage.getTotal(),requestPage.getPageSize(),requestPage.getCurPage(),list);
    }

    /**
     * 删除推荐
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteRecommendUser")
    @ResponseBody
    public Map<String, Object> deleteRecommendUser(@RequestParam(value = "id",required = true) Integer id) {
        try{
            if (id != null && id > 0){
                userService.deleteRecommendUser(id);
            }else{
                return fail("");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return fail("");
        }

        return success("");
    }

    /**
     * 新增推荐
     * @param request
     * @param id
     * @param recommend_id
     * @param example_id
     * @param sort
     * @param status
     * @return
     */
    @RequestMapping(value = "/submitRecommendUser")
    @ResponseBody
    public Map<String, Object> submitRecommendUser(HttpServletRequest request,@RequestParam(value = "id",required = false) Integer id,
                                      @RequestParam(value = "recommend_id",required = true) String recommend_id,
                                      @RequestParam(value = "example_id",required = false) Integer example_id,
                                      @RequestParam(value = "sort",required = false) Integer sort,
                                      @RequestParam(value = "status",defaultValue = "1") Integer status) {
        try{
            ByUserRecommend byUserRecommend = null;
            if (id != null && id > 0){
                byUserRecommend = userService.findRecommendUser(id);
            }else{
                byUserRecommend = new ByUserRecommend();
            }
            User user = userService.findUserByUserName(recommend_id);
            Object temp = request.getSession().getAttribute("login_id");
            Integer userId = temp == null ? 0 : Integer.valueOf(temp.toString());
            byUserRecommend.setUserId(userId);
            byUserRecommend.setRecommendId(user == null ? null : user.getId());
            byUserRecommend.setUserName(recommend_id);
            byUserRecommend.setExampleId(example_id);
            byUserRecommend.setSort(sort);
            byUserRecommend.setStatus(status);
            byUserRecommend.setCreateTime(new DateTime());
            byUserRecommend.setUpdateTime(new DateTime());

            userService.insertRecommendUser(byUserRecommend);
        }catch (Exception ex){
            ex.printStackTrace();
            return fail("");
        }

        return success("");
    }

    /**
     * 获取推荐详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/getByUserRecommend")
    @ResponseBody
    public ByUserRecommend getByUserRecommend(@RequestParam(value = "id",required = false) Integer id){
        return userService.findRecommendUser(id);
    }

    /**
     * 分页查询婚礼预算
     * @param request
     * @param requestPage
     * @param example_id
     * @return
     */
    @RequestMapping(value = "/getExampleBudgetListByPage")
    @ResponseBody
    public ResultPage<ByExampleBudget> getExampleBudgetListByPage(HttpServletRequest request, RequestPage requestPage,
                                                            @RequestParam(value = "example_id", required = false) Integer example_id) {

        List<ByExampleBudget> list = userService.selectExampleBudgetListByPage(example_id,requestPage);

        return new ResultPage<>(requestPage.getTotal(),requestPage.getPageSize(),requestPage.getCurPage(),list);
    }

    /**
     * 婚礼预算详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/getExampleBudget")
    @ResponseBody
    public ByExampleBudget getExampleBudget(@RequestParam(value = "id",required = false) Integer id){
        return userService.selectByExampleBudgetKey(id);
    }

    /**
     * 提交预算
     * @param request
     * @param byExampleBudget
     * @return
     */
    @RequestMapping(value = "/submitExampleBudget")
    @ResponseBody
    public Map<String, Object> submitExampleBudget(HttpServletRequest request,ByExampleBudget byExampleBudget) {
        try{
            ByExampleBudget byExampleBudgetTemp = null;
            if (byExampleBudget.getId() != null && byExampleBudget.getId() > 0){
                byExampleBudgetTemp = userService.selectByExampleBudgetKey(byExampleBudget.getId());
            }else{
                byExampleBudgetTemp = new ByExampleBudget();
            }
            byExampleBudgetTemp.setLevel(byExampleBudget.getLevel());
            byExampleBudgetTemp.setDescn(byExampleBudget.getDescn());
            byExampleBudgetTemp.setExampleId(byExampleBudget.getExampleId());
            byExampleBudgetTemp.setMaterial(byExampleBudget.getMaterial());
            byExampleBudgetTemp.setMoney(byExampleBudget.getMoney());
            byExampleBudgetTemp.setPrice(byExampleBudget.getPrice());
            byExampleBudgetTemp.setUnit(byExampleBudget.getUnit());
            byExampleBudgetTemp.setName(byExampleBudget.getName());
            byExampleBudgetTemp.setNum(byExampleBudget.getNum());
            byExampleBudgetTemp.setCreateTime(new DateTime());
            byExampleBudgetTemp.setUpdateTime(new DateTime());

            userService.insertExampleBudget(byExampleBudgetTemp);
        }catch (Exception ex){
            ex.printStackTrace();
            return fail("");
        }

        return success("");
    }

    /**
     * 删除预算
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteExampleBudget")
    @ResponseBody
    public Map<String, Object> deleteExampleBudget(@RequestParam(value = "id",required = true) Integer id) {
        try{
            if (id != null && id > 0){
                userService.deleteByExampleBudgetKey(id);
            }else{
                return fail("");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return fail("");
        }

        return success("");
    }

    /**
     * 分页查询案例评论
     * @param request
     * @param requestPage
     * @param example_id
     * @return
     */
    @RequestMapping(value = "/getExampleDiscussListByPage")
    @ResponseBody
    public ResultPage<ByExampleDiscuss> getExampleDiscussListByPage(HttpServletRequest request, RequestPage requestPage,
                                                                  @RequestParam(value = "example_id", required = false) Integer example_id) {
        List<ByExampleDiscuss> list = userService.selectExampleDiscussListByPage(example_id,requestPage);

        return new ResultPage<>(requestPage.getTotal(),requestPage.getPageSize(),requestPage.getCurPage(),list);
    }

    /**
     * 案例评论详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/getExampleDiscuss")
    @ResponseBody
    public ByExampleDiscuss getExampleDiscuss(@RequestParam(value = "id",required = false) Integer id){
        return userService.selectByExampleDiscussKey(id);
    }

    /**
     * 提交案例评论
     * @param request
     * @param
     * @return
     */
    @RequestMapping(value = "/submitExampleDiscuss")
    @ResponseBody
    public Map<String, Object> submitExampleDiscuss(HttpServletRequest request,ByExampleDiscuss byExampleDiscuss,
                                                    @RequestParam(value = "file",required = false) MultipartFile file) {
        try{
            ByExampleDiscuss byExampleDiscussTemp = null;
            if (byExampleDiscuss.getId() != null && byExampleDiscuss.getId() > 0){
                byExampleDiscussTemp = userService.selectByExampleDiscussKey(byExampleDiscuss.getId());
            }else{
                byExampleDiscussTemp = new ByExampleDiscuss();
            }
            byExampleDiscussTemp.setName(byExampleDiscuss.getName());
            byExampleDiscussTemp.setContent(byExampleDiscuss.getContent());
            byExampleDiscussTemp.setExampleId(byExampleDiscuss.getExampleId());
            if (file != null && file.getSize() > 0){
                if(file.getSize()>10000000)
                {
                    throw new Exception("上传失败：文件大小不能超过10M");
                }

                String fileName = file.getOriginalFilename();
                int  indexdot =  fileName.lastIndexOf(".");
                String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+fileName.substring(indexdot);

//                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
                UploadUtil.uploadData(file.getBytes(), img_url);
                byExampleDiscussTemp.setImgUrl(img_url);
            }
            byExampleDiscussTemp.setScore(byExampleDiscuss.getScore());
            byExampleDiscussTemp.setCreateTime(new DateTime());
            byExampleDiscussTemp.setUpdateTime(new DateTime());

            userService.insertExampleDiscuss(byExampleDiscussTemp);
        }catch (Exception ex){
            ex.printStackTrace();
            return fail("");
        }

        return success("");
    }

    /**
     * 删除案例评论
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteExampleDiscuss")
    @ResponseBody
    public Map<String, Object> deleteExampleDiscuss(@RequestParam(value = "id",required = true) Integer id) {
        try{
            if (id != null && id > 0){
                userService.deleteByExampleDiscussKey(id);
            }else{
                return fail("");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return fail("");
        }

        return success("");
    }

    /**
     * 分页查询字典表
     * @param request
     * @param requestPage
     * @param type
     * @return
     */
    @RequestMapping(value = "/getDictListByPage")
    @ResponseBody
    public ResultPage<Dict> getDictListByPage(HttpServletRequest request, RequestPage requestPage,
                                                                  @RequestParam(value = "type", required = false) Integer type) {

        List<Dict> list = userService.selectDictListByPage(type,requestPage);

        return new ResultPage<>(requestPage.getTotal(),requestPage.getPageSize(),requestPage.getCurPage(),list);
    }

    /**
     * 字典表详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/getDict")
    @ResponseBody
    public Dict getDict(@RequestParam(value = "id",required = false) Integer id){
        return userService.selectByDictKey(id);
    }

    /**
     * 提交字典表
     * @param request
     * @param dict
     * @return
     */
    @RequestMapping(value = "/submitDict")
    @ResponseBody
    public Map<String, Object> submitDict(HttpServletRequest request,Dict dict) {
        try{
            Dict dictTemp = null;
            if (dict.getId() != null && dict.getId() > 0){
                dictTemp = userService.selectByDictKey(dict.getId());
            }else{
                dictTemp = new Dict();
            }
            dictTemp.setType(dict.getType());
            dictTemp.setCode(dict.getCode());
            dictTemp.setName(dict.getName());

            userService.insertDict(dictTemp);
        }catch (Exception ex){
            ex.printStackTrace();
            return fail("");
        }

        return success("");
    }

    /**
     * 删除字典表
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteDict")
    @ResponseBody
    public Map<String, Object> deleteDict(@RequestParam(value = "id",required = true) Integer id) {
        try{
            if (id != null && id > 0){
                userService.deleteByDictKey(id);
            }else{
                return fail("");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return fail("");
        }

        return success("");
    }
}
